import pageination from '../../components/pageination/pageination.vue'
export default {
	data() {
		return {
		  id: 0,
      userId: 0,
      validate: {}, //验证对象
      expertGender: 0,
      uuid: 0,
      thatUrl: this.urls.baseUrl,
      headPortrait: '',
			total: 0,
			size: 10,
			page: 1,
			expertInfo: [],
			queryType: "expertName", //数据
			content: '',
			loadMore: {
				queryType: "expertName",
				content: null,
			},
			type0: [],
			type1: [],
			type2: [],
			//			total: 0, //总条数
			//			page: 1, //当前页
			//			size: 10,//每页显示条数
			ApplicationStatus: false,
			Application: false,
			curId: 0,
			uploadNum: 0,
			newOrUpdate: {}, // 对象
      tempTheWork: "", //临时身份证号信息（用于校验）
      tempPhone: "", //临时手机号信息（用于校验）
			newExpertResources: [],
			toExpertView: null,
			isModify:false,//true 修改  false新增
			curIndex:-1,//选中下标
		}
	},
	components: {
		pageination
	},
	created() { //调用方法

		this.newExpertResources = [];
		this.type0 = [];
		this.type1 = [];
		this.type2 = [];
		this.findPageExperts();
	},
	mounted() {
    let that = this;
	  jQuery.validator.addMethod("isMobile", function(value, element) {
      let length = value.length;
      let mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
      return this.optional(element) || (length == 11 && mobile.test(value));
    }, "请正确填写手机号码");

    //校验手机号重复
    jQuery.validator.addMethod("checkPhoneRepeat", function(value, element, params) {
      let flg = false;
      if(value == that.tempPhone) {
        flg = true;
      } else {
        $.ajax({
          type: "POST",
          async: false,
          url: that.urls.queryHeavy,
          data: JSON.stringify({
            "userPhoneNumber": value
          }),
          dataType: "json",
          contentType: "application/json",
          success: function(data) {
            flg = !data.success
          }
        });
      }
      return this.optional(element) || flg;
    }, "该手机号已存在！");

    //校验身份证重复
    jQuery.validator.addMethod("checkTheWorkRepeat", function(value, element, params) {
      let flg = false;
      if(value == that.tempTheWork) {
        flg = true;
      } else {
        $.ajax({
          type: "POST",
          async: false,
          url: that.urls.queryHeavy,
          data: JSON.stringify({
            "userAccount": value
          }),
          dataType: "json",
          contentType: "application/json",
          success: function(data) {
            flg = !data.success
          }
        });
      }
      return this.optional(element) || flg;
    }, "该身份证号已存在！")

    //加载表单验证
    this.validate = $("#expertsForm").validate({
      ignore: [],
      rules: {
        expertName: { // 名称
          required: true,
          maxlength: 10
        },
        theWork: { // 身份证
          required: true,
          maxlength: 19,
          minlength: 18,
          checkTheWorkRepeat: true
        },
        email: { // 邮箱
          required: true,
          maxlength: 32,
          email: true
        },
        expertGender: { // 性别
          required: true,
        },
        expertUnit: { // 所在单位
          required: true,
          maxlength: 50,
        },
        phoneNumber: { // 手机
          required: true,
          isMobile : true,
          checkPhoneRepeat: true
        },
        tutorClasses: { // 手机
          //required: true,
          maxlength: 10
        },

        firestLevel:{
          //required: true,
          maxlength: 10,
        },
        secondLevel:{
         required: true,
          maxlength: 10,
        },
        partyPolicyDuty:{
          maxlength: 50
        },
        professionalSkillDuty:{
          maxlength: 10,
        },
       /* professionalSkillDutyLevel:{
          maxlength: 10,
        },*/


      },
      messages: {
        expertName: { // 名称
          required: "请输入名称",
          maxlength: "请输入长度小于10"
        },
        theWork: { // userAccount
          required: "请输入身份证",
          maxlength: "请输入长度小于19",
          minlength: '最小长度不小于18'
        },
        email: { // 邮箱
          required: "请输入邮箱",
          maxlength: "请输入长度小于32",
          email: '请输入正确的邮箱'
        },
        expertUnit: { // 角色
          required: "请输入所在单位",
          maxlength: '所在单位最大长度为50',
        },
        phoneNumber: { // 手机号
          required: "请输入手机号",
          isMobile : '请输入正确的手机号码!'
        },
        expertGender: { // 性别
          required: "请选择性别",
        },
        tutorClasses: { // 密码
          //required: "请输入导师类别",
          maxlength: '最大长度为10',
        },

        firestLevel:{
          //required: '请输入一级学科',
          maxlength: '最大长度为10',
        },
        secondLevel:{
          required: '请输入二级学科',
          maxlength: '最大长度为10',
        },
        partyPolicyDuty:{
          maxlength: '最大长度为50',
        },
        professionalSkillDuty:{
          maxlength: '最大长度为10',
        },
        /*professionalSkillDutyLevel:{
          maxlength: '最大长度为10',
        },*/
      },
     /* errorElement: "em",
      errorPlacement: function(error, element) {
        error.appendTo(element.parents(".error-box").children(".error-msg"));
      }*/
    });
  },
	methods: { //写函数方法
		//给选中的列加背景色
		choosed:function(index){
			this.curIndex=index;
		},
		//分页模糊查询
		findPageExperts: function() {
			let that = this;
	    let name = $('#searchName').val();

	    let obj =   {"pageNum": that.page,"pageSize": that.size };
      obj[name] = that.content;
			that.$post(
				that.urls.findPageExperts,
          obj
			).then(function(res) {
				if(res.success) {
						that.page = res.pageInfo.pageNum;
						that.size = res.pageInfo.pageSize;
						that.total = res.pageInfo.total;
						that.expertInfo = res.pageInfo.list;
				}
			})
		},

		queryPageExperts: function() {
			this.page = 1;
			this.size = 10;
			this.loadMore.queryType = this.queryType;
			this.loadMore.content = this.content;
			this.findPageExperts();



		},
		//页码切换执行方法
		pageFn: function(val, pid) {
			this.page = parseInt(val);
			this.findPageExperts();
			//此处调列表数据接口
		},
		/**返回子组件用户选择的一页显示条数**/
		obtainChild: function(data) {
			this.row = data;
		},

		//新增或修改专家信息
		newOrUpdateExpert: function() {
      let that = this;

      let flg = that.validate.form();

      if(! flg){
        return;
      }

      let dataObj = that.combinationFormObject(that.validate.currentForm);
      if(that.id){
        dataObj.id = that.id;
      }

      that.$post(    // experts 查重
        that.urls.expertQueryHeavy,
           dataObj
      )
        .then(function(res) {
          if(res.success) {
            layer.msg('身份证已存在，请重新输入', {
              time: 3000, //3s后自动关闭
            });
          }else {

            that.$post(  // user查重
              that.urls.queryHeavy,
              {userAccount: dataObj.theWork, "id": that.userId}
            )
              .then(function(res) {
                if(res.success) {
                  layer.msg(res.data, {
                    time: 3000, //3s后自动关闭
                  });
                }else {

                  // ok
                  if(null != that.newExpertResources) {
                    dataObj.expertResources = that.newExpertResources;
                  }
                  that.$post( // 专家add或者upd
                    that.urls.newOrUpdateExpert,
                    dataObj
                  ).then(function(res) {
                    if(res.success) {
                      layer.msg(res.message, {
                        time: 3000, //3s后自动关闭
                      });
                      that.Application = false;
                      that.ApplicationStatus = false;
                      that.findPageExperts();

                      if(that.userId){
                        dataObj.id = that.userId;
                        that.$post(
                          that.urls.editExpertsUser,
                          dataObj
                        )
                          .then(function(res) {
                            if(res.success) {

                            }
                          })

                      }

                    } else {
                      alert(res.message)
                    }
                  })

                  // ok end

                }
              })
          }
        })


		},

		//人工录入及修改模态框
		manually: function(d) {
      $("#expertsForm").validate().resetForm();
      $("input[type='reset']").trigger("click");
		  let that = this;
      that.type0 = [];
      that.type1 = [];
      that.type2 = [];
		  that.curId = 0;
      that.userId = 0;
      $("#imgHand").attr('src','  ');
		  that.id = 0;
			this.newOrUpdate = d;
			this.tempTheWork = d.theWork;
      this.tempPhone = d.phoneNumber;
			this.newExpertResources = [];
			if(d.id > 0) {
			  that.userId = d.userId;
			  that.id = d.id;
				that.findResources(d.id);
        that.expertGender = d.expertGender;
         if(d.headPortrait != ' ' && d.headPortrait){
           $('#imgHand').attr('src',that.thatUrl + d.headPortrait);
         }else {
           $('#imgHand').attr('src',' ');
         }
			}
			this.ApplicationStatus = true;
			if(d.expertName){
				this.isModify=true;
			}else{
				this.isModify=false;
			}
		},
		//查看
		toView: function(d) {
      let that = this;
      that.headPortrait =  ' ';
			this.toExpertView = d;
			this.newExpertResources = [];
			this.findResources(this.toExpertView.id);
			this.Application = true;
      if(d.headPortrait){
        that.headPortrait =  that.thatUrl + d.headPortrait;
      }

		},
		//关闭模态框
		closeModel: function() {
			this.type0 = [];
			this.type1 = [];
			this.type2 = [];
			this.newOrUpdate = {};
			this.Application = false;
			this.ApplicationStatus = false;
			this.newExpertResources = [];

		},
		touchOffIdInput(n) {
			this.uploadNum = n;
			if(n == 1) {
				$("#handIdFront").click();
			}
		},

    // 上传头像
    idFrontImg: function(event) {
      let that = this;
      let files = event.currentTarget.files;
      if (!that.fileGlobalFilter(files)) {
        return;
      }
      let formData = new FormData();
      for(let i = 0, len = files.length; i < len; i++) {
        formData.append('fileNames', files[i]);
      }
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.upload,
        formData,
        config
      )
        .then(function(res) {
          if(res.success) {
            let fileInfos = res.data;
            let urls = [];
            //  let names = [];
            let enclosureList = [];  // 查看
            for(let i = 0, len = fileInfos.length; i < len; i++) {
              urls.push(fileInfos[i].url);
              //   names.push(that.getFileName(fileInfos[i].url));
              enclosureList.push({
                "name": that.getFileName(fileInfos[i].url),
                "url":  fileInfos[i].url
              });

            }
            that.FileUpload = enclosureList;
            that.headPortrait = urls.join(";");
             console.log( that.thatUrl + that.headPortrait)
            $('#imgHand').attr('src',that.thatUrl + that.headPortrait);

          }
        })
    },
	/*点击调用上传控件*/
	uploadFileMiddle:function(n){
		$(".upload-img"+n).click();
	},
//上传文件
		uploadFile: function(t, event) {
			var that = this;
			var file = event.currentTarget.files[0];
			let formData = new FormData();
			formData.append('fileNames', file);
			let config = {
				headers: {
					'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
				}
			};
			that.$post(
					that.urls.uploadExpert,
					formData,
					config
				)
				.then(function(res) {
					if(res.success) {
						layer.msg(res.message, {
							time: 3000, //3s后自动关闭
						});
						res.data.type = t;
						switch(t) {
							case 0:
								that.type0.push(res.data);
								break;
							case 1:
								that.type1.push(res.data);
								break;
							case 2:
								that.type2.push(res.data);
								break;
						}
						that.newExpertResources.push(res.data);
					} else {
						layer.msg(res.message, {
							time: 3000, //3s后自动关闭
						});
					}
				})
		},

		//删除资源信息
		deleteResources: function(expertId, i, uuid, arr) {
      let that = this;
      let id = i;
      console.log(that.type0)
       console.log('专家id'+expertId)
      console.log('文件id'+i)
      console.log('uuid:'+ uuid)
      layer.confirm('你确定要删除吗?', {icon: 3, title:'提示'}, function(index){
        if(null != id) {
          that.$post(
            that.urls.deleteResources, {
              "id": id,
            }

          )
            .then(function(res) {
              if(res.success) {
                layer.msg(res.message, {
                  time: 3000, //3s后自动关闭
                });
                that.findResources(that.id);
              } else {
                layer.msg("删除失败", {
                  time: 3000, //3s后自动关闭
                });
              }




            })
        }else {
           if(arr){
             let list = [];
             arr.forEach(function (e) {
                if(e.uuid != uuid){
                  list.push(e);
                }
             })

             // 在删除文件
             that.$post(
               that.urls.findResources, {
                 "expertId": that.id,
               }

             )
               .then(function(res) {
                 if(res.success) {
                   if(that.curId === 0){
                      if(res.data.textList && res.data.textList.length >0){
                        res.data.textList.forEach(function (e) {
                          if(e.uuid === uuid){
                            that.delAttr(e.id);
                          }
                        })
                      }
                     that.type0 = list;
                   }else if(that.curId === 1){
                     if(res.data.pictureList && res.data.pictureList.length >0){
                       res.data.pictureList.forEach(function (e) {
                         if(e.uuid === uuid){
                           that.delAttr(e.id);
                         }
                       })
                     }
                     that.type1 = list;
                   }else if(that.curId === 2){
                     if(res.data.videoList && res.data.videoList.length >0){
                       res.data.videoList.forEach(function (e) {
                         if(e.uuid === uuid){
                           that.delAttr(e.id);
                         }
                       })
                     }
                     that.type2 = list;
                   }

                     layer.msg('删除成功!', {
                       time: 3000, //3s后自动关闭
                     });
                 }else {
                   layer.msg('删除失败!', {
                     time: 3000, //3s后自动关闭
                   });
                 }
               })

           }


        }
      });


		},

		//通过专家id更新资源信息
		findResources: function(id) {
			var that = this;
			that.$post(
					that.urls.findResources, {
						"expertId": id,
					}

				)
				.then(function(res) {
					if(res.success) {
						that.type0 = res.data.textList;
						that.type1 = res.data.pictureList;
						that.type2 = res.data.videoList;
					} else {
						layer.msg(res.message, {
							time: 3000, //3s后自动关闭
						});

					}
				})
		},
		//下载资源
    downloadResources: function(filePath) {
		 let urls = filePath.replace('\\' ,"/");
      let ur = urls.replace('\\' ,"/");

      if(filePath != null && filePath != "") {
        window.location.href = this.urls.download + "?path=" +  ur ;
      }

    },



    // 跳转到预览
    toSrc: function (url) {
      if(url == null || url == undefined || url == ''){
        layer.msg('暂无附件', {
          time: 3000, //3s后自动关闭
        });
        return;
      }
      window.open(this.thatUrl + url);
    },
    delAttr: function (id) {
	  let that = this;
      that.$post(
        that.urls.deleteResources, {
          "id": id,
        }

      )
        .then(function(res) {


        })
    },
    //导出数据
    exportData: function() {
      window.location.href = this.urls.exportExcel + "?" + this.queryType + "=" + this.content;
    },
    //导入数据
    inputData: function (event) {
      let that = this;
      var file = event.currentTarget.files[0];
      if (!that.fileGlobalFilter(file)) {
        return;
      }
      let formData = new FormData();
      formData.append('fileNames', file);
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
        }
      };
      that.$post(
        that.urls.importExcel,
        formData,
        config
      )
      .then(function(res) {
        let msg = '';
        if(res.success) {
          msg = "导入成功！";
          that.findPageExperts();
        } else {
          msg = res.message;
        }
        layer.msg(msg, {
          time: 3000, //3s后自动关闭
        });
      })
    }
	}
}
